package top.xbaoziplus.company.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import top.xbaoziplus.company.common.Result;
import top.xbaoziplus.company.empty.UserInfo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xBaozi
 * @version 1.0
 * @classname LoginCheckFilter
 * @description 登录状态检查拦截器
 * @date 2022/4/28 0:28
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    /** 路径匹配器，支持通配符 */
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * @description 检查用户是否完成登录
     * @author xBaozi
     * @date 0:34 2022/4/28
     **/
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 响应参数格式设置
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("application/json");

        // 类型强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求路径URI
        String requestURI = request.getRequestURI();

        // 定义需要跳过拦截的请求路径
        String[] urlsWithPass = new String[] {
                "/user/login",
                "/user/register",
                "/user/sendMsg",
                "/v2/api-docs",
                "/swagger",
                "/swagger-ui.html",
                "/favicon.ico",
                "/webjars/"
        };

        // 检查是否为跳过拦截路径
        boolean checkForPass = check(urlsWithPass, requestURI);

        // 判断为需要跳过的路径，直接放行
        if (checkForPass) {
            log.info("本次跳过拦截的路径：{}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        // 判断用户是否已登录
        UserInfo user = (UserInfo)request.getSession().getAttribute("user");
        if (user != null) {
            log.info("用户{}已登录", user.getName());
            filterChain.doFilter(request, response);
            return;
        }

        // 请求路径为拦截路径且用户未登录
        log.info("用户未登录，本次拦截路径{}不支持被访问", requestURI);
        // 前端存在根据NOTLOGIN进行判断拦截
        response.getWriter().write(JSON.toJSONString(Result.fail("未登录")));
    }

    /**
     * @description 检查请求路径是否为跳过拦截的路径
     * @author xBaozi
     * @date 0:37 2022/4/28
     * @param urls          需要跳过拦截的路径
     * @param requestURI    需要检查的请求路径
     * @return  成功匹配是需要跳过的返回true，否则false
     **/
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            // 调用AntPathMatch对象中match进行匹配
            if (PATH_MATCHER.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
